<template>
  <view class="register-page">
    <!-- 背景动画元素 -->
    <view class="bg-bubbles">
      <view class="bubble" v-for="i in 5" :key="i" :style="bubbleStyle(i)"></view>
    </view>
    
    <!-- 头部Logo区域 -->
    <view class="register-header">
      <image class="logo" src="@/components/zhq-login/images/logo.png" mode="aspectFill"></image>
      <text class="register-title">欢迎注册</text>
      <text class="register-subtitle">创建您的专属账号</text>
    </view>
    
    <!-- 注册表单 -->
    <view class="register-form">
      <!-- 用户ID -->
      <view class="form-item" @touchstart="startInputAnimation($event, 'userId')">
        <view class="form-item-label">
          <image src="@/components/zhq-login/images/cellphone.png" mode="aspectFit"></image>
        </view>
        <view class="form-item-input">
          <input 
            type="text" 
            v-model.trim="userId" 
            placeholder="请输入用户ID"
            placeholder-class="placeholder"
            :class="{'error': userIdError, 'active': activeInput === 'userId'}"
            @focus="setActiveInput('userId')"
            @blur="validateUserId"
          />
          <text v-if="userIdError" class="error-tip">{{userIdErrorMsg}}</text>
        </view>
        <view class="input-highlight" :class="{'animate': activeInput === 'userId'}"></view>
      </view>
      
      <!-- 密码 -->
      <view class="form-item" @touchstart="startInputAnimation($event, 'password')">
        <view class="form-item-label">
          <image src="@/components/zhq-login/images/tapered.png" mode="aspectFit"></image>
        </view>
        <view class="form-item-input">
          <input 
            type="password" 
            v-model.trim="password" 
            placeholder="请设置密码 (6-16位字母+数字)"
            placeholder-class="placeholder"
            :class="{'error': passwordError, 'active': activeInput === 'password'}"
            @focus="setActiveInput('password')"
            @blur="validatePassword"
          />
          <text v-if="passwordError" class="error-tip">{{passwordErrorMsg}}</text>
        </view>
        <view class="input-highlight" :class="{'animate': activeInput === 'password'}"></view>
      </view>
      
      <!-- 确认密码 -->
      <view class="form-item" @touchstart="startInputAnimation($event, 'confirmPassword')">
        <view class="form-item-label">
          <image src="@/components/zhq-login/images/tapered.png" mode="aspectFit"></image>
        </view>
        <view class="form-item-input">
          <input 
            type="password" 
            v-model.trim="confirmPassword" 
            placeholder="请确认密码"
            placeholder-class="placeholder"
            :class="{'error': confirmPasswordError, 'active': activeInput === 'confirmPassword'}"
            @focus="setActiveInput('confirmPassword')"
            @blur="validateConfirmPassword"
          />
          <text v-if="confirmPasswordError" class="error-tip">{{confirmPasswordErrorMsg}}</text>
        </view>
        <view class="input-highlight" :class="{'animate': activeInput === 'confirmPassword'}"></view>
      </view>
      
      <!-- 注册按钮 -->
      <view class="register-btn" 
            @click="registerSubmit" 
            :class="{'disabled': !isFormValid || loading}"
            @touchstart="startBtnAnimation"
            @touchend="endBtnAnimation"
            :style="btnScale">
        <text v-if="!loading">立即注册</text>
        <view v-else class="loading">
          <view class="loading-spinner"></view>
          <text>注册中...</text>
        </view>
        <view class="btn-ripple" v-if="showRipple" :style="rippleStyle"></view>
      </view>
      
      <!-- 已有账号提示 -->
      <view class="login-tip">
        已有账号？<text class="login-link" @click="goToLogin">立即登录</text>
      </view>
    </view>
    
    <!-- 成功注册时的庆祝动画 -->
    <view class="confetti-container" v-if="showConfetti">
      <view class="confetti" v-for="(item, index) in confettiItems" :key="index" :style="item.style"></view>
    </view>
  </view>
</template>

<script>
import { registerAPI } from '@/utils/request.js';

export default {
  data() {
    return {
      userId: '',
      password: '',
      confirmPassword: '',
      loading: false,
      activeInput: '',
      
      // 动画相关状态
      btnScale: 'transform: scale(1)',
      showRipple: false,
      rippleStyle: '',
      confettiItems: [],
      showConfetti: false,
      
      // 表单验证状态
      userIdError: false,
      userIdErrorMsg: '',
      passwordError: false,
      passwordErrorMsg: '',
      confirmPasswordError: false,
      confirmPasswordErrorMsg: ''
    };
  },
  computed: {
    // 表单是否有效
    isFormValid() {
      return (
        this.userId && 
        this.password && 
        this.confirmPassword && 
        this.password === this.confirmPassword
      );
    }
  },
  methods: {
    // 提示信息
    msg(msg) {
      uni.showToast({
        title: msg,
        icon: 'none',
        position: 'top'
      });
    },
    
    // 设置当前活跃的输入框
    setActiveInput(field) {
      this.activeInput = field;
    },
    
    // 输入框点击动画
    startInputAnimation(event, field) {
      this.activeInput = field;
      const query = uni.createSelectorQuery().in(this);
      query.select(`.form-item:nth-child(${['userId', 'password', 'confirmPassword'].indexOf(field) + 1})`).boundingClientRect(data => {
        if (data) {
          const x = event.touches[0].clientX - data.left;
          const y = event.touches[0].clientY - data.top;
          this.$nextTick(() => {
            const highlight = document.querySelector(`.form-item:nth-child(${['userId', 'password', 'confirmPassword'].indexOf(field) + 1}) .input-highlight`);
            if (highlight) {
              highlight.style.left = `${x}px`;
              highlight.style.top = `${y}px`;
            }
          });
        }
      }).exec();
    },
    
    // 按钮按下动画
    startBtnAnimation(event) {
      if (this.loading || !this.isFormValid) return;
      
      this.btnScale = 'transform: scale(0.98)';
      
      // 创建涟漪效果
      const btn = event.currentTarget;
      const rect = btn.getBoundingClientRect();
      const x = event.touches[0].clientX - rect.left;
      const y = event.touches[0].clientY - rect.top;
      
      this.showRipple = true;
      this.rippleStyle = `left: ${x}px; top: ${y}px;`;
    },
    
    // 按钮释放动画
    endBtnAnimation() {
      this.btnScale = 'transform: scale(1)';
      setTimeout(() => {
        this.showRipple = false;
      }, 600);
    },
    
    // 生成气泡样式
    bubbleStyle(index) {
      const size = Math.random() * 40 + 20;
      const posX = Math.random() * 100;
      const posY = Math.random() * 100;
      const delay = Math.random() * 5;
      const duration = Math.random() * 10 + 10;
      
      return {
        width: `${size}px`,
        height: `${size}px`,
        left: `${posX}%`,
        top: `${posY}%`,
        animationDelay: `${delay}s`,
        animationDuration: `${duration}s`,
        opacity: Math.random() * 0.2 + 0.05
      };
    },
    
    // 创建庆祝彩花效果
    createConfetti() {
      this.confettiItems = [];
      const colors = ['#3588da', '#4a9fe8', '#ff6b6b', '#ffa502', '#2ed573', '#ff7f50'];
      
      for (let i = 0; i < 50; i++) {
        this.confettiItems.push({
          style: {
            backgroundColor: colors[Math.floor(Math.random() * colors.length)],
            left: `${Math.random() * 100}%`,
            top: `${Math.random() * 100}%`,
            width: `${Math.random() * 10 + 5}px`,
            height: `${Math.random() * 10 + 5}px`,
            transform: `rotate(${Math.random() * 360}deg)`,
            animationDelay: `${Math.random() * 0.5}s`,
            animationDuration: `${Math.random() * 3 + 2}s`
          }
        });
      }
      
      this.showConfetti = true;
      setTimeout(() => {
        this.showConfetti = false;
      }, 3000);
    },
    
    // 验证用户ID
    validateUserId() {
      if (!this.userId) {
        this.userIdError = true;
        this.userIdErrorMsg = '请输入用户ID';
        return false;
      } else if (this.userId.length < 1) {
        this.userIdError = true;
        this.userIdErrorMsg = '用户ID不能为空！';
        return false;
      } else {
        this.userIdError = false;
        return true;
      }
    },
    
    // 验证密码
    validatePassword() {
      const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/;
      if (!this.password) {
        this.passwordError = true;
        this.passwordErrorMsg = '请设置密码';
        return false;
      } else if (this.password.length < 6) {
        this.passwordError = true;
        this.passwordErrorMsg = '密码长度不能小于6位';
        return false;
      } else if (!reg.test(this.password)) {
        this.passwordError = true;
        this.passwordErrorMsg = '密码需包含字母和数字';
        return false;
      } else {
        this.passwordError = false;
        return true;
      }
    },
    
    // 验证确认密码
    validateConfirmPassword() {
      if (!this.confirmPassword) {
        this.confirmPasswordError = true;
        this.confirmPasswordErrorMsg = '请确认密码';
        return false;
      } else if (this.confirmPassword !== this.password) {
        this.confirmPasswordError = true;
        this.confirmPasswordErrorMsg = '两次密码输入不一致';
        return false;
      } else {
        this.confirmPasswordError = false;
        return true;
      }
    },
    
    // 注册提交
    async registerSubmit() {
      // 表单验证
      const userIdValid = this.validateUserId();
      const passwordValid = this.validatePassword();
      const confirmPasswordValid = this.validateConfirmPassword();
      
      if (!userIdValid || !passwordValid || !confirmPasswordValid) {
        return;
      }
      
      this.loading = true;
      
      try {
        // 调用后端注册API
        const response = await registerAPI(this.userId, this.password);
        
        if (response.code === 200) {
          this.createConfetti();
          this.msg('注册成功');
          setTimeout(() => {
            this.goToLogin();
          }, 1500);
        } else {
          this.msg(response.message || '注册失败');
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        this.msg('注册失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    },
    
    // 跳转到登录页
    goToLogin() {
      uni.reLaunch({ url: '/pages/index/login' });
    }
  }
};
</script>

<style lang="scss">
.register-page {
  padding: 0 60rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

/* 背景气泡动画 */
.bg-bubbles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.bubble {
  position: absolute;
  background: rgba(53, 136, 218, 0.1);
  border-radius: 50%;
  animation: floatUp linear infinite;
}

@keyframes floatUp {
  0% {
    transform: translateY(100vh) scale(0.5);
    opacity: 0;
  }
  10% {
    opacity: 0.1;
  }
  100% {
    transform: translateY(-100px) scale(1);
    opacity: 0;
  }
}

.register-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0 40rpx;
  position: relative;
  z-index: 2;
  animation: fadeInDown 0.8s ease-out;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(53, 136, 218, 0.2);
  transform: scale(0);
  animation: zoomIn 0.6s 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
}

.register-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  opacity: 0;
  transform: translateY(20rpx);
  animation: fadeInUp 0.5s 0.5s ease-out forwards;
}

.register-subtitle {
  font-size: 28rpx;
  color: #888;
  opacity: 0;
  transform: translateY(20rpx);
  animation: fadeInUp 0.5s 0.7s ease-out forwards;
}

.register-form {
  width: 100%;
  background-color: #fff;
  border-radius: 24rpx;
  padding: 50rpx 40rpx;
  box-sizing: border-box;
  margin: 40rpx 0;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 2;
  opacity: 0;
  transform: translateY(30rpx);
  animation: fadeInUp 0.6s 0.8s ease-out forwards;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
  overflow: hidden;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item-label {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  transition: all 0.3s;
}

.form-item-label image {
  width: 40rpx;
  height: 40rpx;
  transition: all 0.3s;
}

.form-item-input {
  flex: 1;
  position: relative;
}

.form-item-input input {
  width: 100%;
  height: 80rpx;
  font-size: 30rpx;
  color: #333;
  padding: 0 10rpx;
  transition: all 0.3s;
}

.form-item-input input.active {
  transform: translateX(10rpx);
}

.form-item-input input.active + .form-item-label image {
  transform: scale(1.2);
}

.placeholder {
  color: #bbb;
  font-size: 28rpx;
}

.error {
  border-bottom: 2rpx solid #ff4d4f;
}

.error-tip {
  position: absolute;
  left: 0;
  bottom: -40rpx;
  font-size: 24rpx;
  color: #ff4d4f;
  line-height: 1.5;
  animation: shake 0.5s;
}

.input-highlight {
  position: absolute;
  width: 20rpx;
  height: 20rpx;
  background: rgba(53, 136, 218, 0.2);
  border-radius: 50%;
  transform: scale(0);
  pointer-events: none;
}

.input-highlight.animate {
  animation: ripple 0.6s ease-out;
}

@keyframes ripple {
  to {
    transform: scale(20);
    opacity: 0;
  }
}

.register-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(90deg, #3588da, #4a9fe8);
  color: #fff;
  border-radius: 45rpx;
  text-align: center;
  font-size: 34rpx;
  font-weight: 500;
  margin-top: 70rpx;
  box-shadow: 0 8rpx 20rpx rgba(53, 136, 218, 0.3);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.register-btn.disabled {
  background: #d9d9d9;
  box-shadow: none;
}

.btn-ripple {
  position: absolute;
  width: 20rpx;
  height: 20rpx;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 50%;
  transform: scale(0);
  animation: ripple 0.6s ease-out;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 36rpx;
  height: 36rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s linear infinite;
  margin-right: 15rpx;
}

.login-tip {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  margin-top: 50rpx;
  opacity: 0;
  animation: fadeIn 0.5s 1.5s forwards;
}

.login-link {
  color: #3588da;
  font-weight: 500;
  margin-left: 10rpx;
  position: relative;
}

.login-link:after {
  content: '';
  position: absolute;
  bottom: -4rpx;
  left: 0;
  width: 0;
  height: 2rpx;
  background: #3588da;
  transition: width 0.3s;
}

.login-link:active:after {
  width: 100%;
}

/* 庆祝彩花动画 */
.confetti-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 100;
}

.confetti {
  position: absolute;
  opacity: 0;
  animation: confettiFall linear forwards;
}

@keyframes confettiFall {
  0% {
    transform: translateY(-100px) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(100vh) rotate(360deg);
    opacity: 0;
  }
}

/* 通用动画 */
@keyframes fadeIn {
  to { opacity: 1; }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes zoomIn {
  from {
    transform: scale(0);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  20%, 60% { transform: translateX(-10rpx); }
  40%, 80% { transform: translateX(10rpx); }
}

/* 表单项入场动画 */
.form-item {
  opacity: 0;
  transform: translateY(30rpx);
}

@for $i from 1 through 5 {
  .form-item:nth-child(#{$i}) {
    animation: fadeInUp 0.5s #{0.3s + ($i * 0.1s)} ease-out forwards;
  }
}
</style>